import { Component, OnInit } from '@angular/core';
import { remove as _remove } from 'lodash';

@Component({
  selector: 'app-demo5',
  templateUrl: './demo5.component.html',
  styles: [
    `
      .customer-transfer {
        width: 8.12rem;
        height: 4rem;
      }
      .transfer-checkbox-content {
        width: 100%;
      }
      .transfer-checkbox-item {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        width: 100%;
        padding: 0 0.08rem;
        border-bottom: 0.01rem solid #f2f2f2;
      }
      .transfer-checkbox-target-item {
        justify-content: space-between;
      }
      .transfer-checkbox-item:hover {
        background-color: #f7f7f7;
      }
      .transfer-checkbox-item-remove {
        flex-shrink: 0;
        margin-left: 0.08rem;
        cursor: pointer;
      }
      ::ng-deep .lv-transfer-default .lv-transfer-panel-body .transfer-checkbox-item {
        height: 0.4rem;
      }
      ::ng-deep .lv-transfer-small .lv-transfer-panel-body .transfer-checkbox-item {
        height: 0.32rem;
      }
      ::ng-deep .lv-transfer-large .lv-transfer-panel-body .transfer-checkbox-item {
        height: 0.56rem;
      }
    `,
  ],
})
export class Demo5Component implements OnInit {
  source: { data: any[]; selection: any[] } = {
    data: [],
    selection: [],
  };
  selection = ['item2'];

  constructor() {}

  ngOnInit() {
    this.initData();
  }

  initData() {
    this.source.data = this.getSourceData(50);
    this.source.selection = [...this.convertSelection(this.source.data, this.selection)];
  }

  getSourceData(len) {
    return Array.from({ length: len }).map((item, key) => {
      return {
        key: `item${key + 1}`,
        value: `item${key + 1}`,
        label: `content${key + 1}`,
        description: `description of content${key + 1}`,
        direction: Math.random() * 2 > 1 ? 'right' : undefined,
      };
    });
  }

  change(selection) {
    this.source.selection = [...this.convertSelection(this.source.data, selection)];
  }

  selectionChange(event) {
    const { selection } = event;

    this.selection.length = 0;
    this.source.selection.length = 0;

    selection.forEach(item => {
      this.selection.push(item.value);
      this.source.selection.push(item);
    });

    this.selection = [...this.selection];
    this.source.selection = [...this.source.selection];
  }

  remove(item) {
    const deleteKey = item.value;

    _remove(this.source.selection, s => s.value === deleteKey);
    _remove(this.selection, s => s === deleteKey);

    this.source.selection = [...this.source.selection];
    this.selection = [...this.selection];
  }

  convertSelection(data, value) {
    const dataMap = new Map();
    const selection = [];

    data.forEach(item => {
      dataMap.set(item.value, item);
    });

    value.forEach(s => {
      selection.push(dataMap.get(s));
    });

    return selection;
  }
}
